import React, { useState, useEffect } from "react";
import {
  Button,
  TextField,
  Box,
  Typography,
  Grid,
  ThemeProvider,
  Avatar,
  createTheme,
  InputAdornment,
  IconButton,
} from "@mui/material";
import { Link, useSubmit, useNavigate, useActionData } from "react-router-dom";
import LockOutlinedIcon from "@mui/icons-material/LockOutlined";
import { Visibility, VisibilityOff } from "@mui/icons-material";
import { Copyright, LilySnack } from "../../components/common/Common.jsx";
import {
  registerUser,
  validateRegisterData,
} from "../../api/userLoginRegister.js";
import LoginRegisterContainer from "./Common.jsx";
/**
 * Sign in action function
 * @param {request} request data
 * @returns redirect if successful, id if failed
 */
export async function action({ request }) {
  const formData = await request.formData();
  const nickname = formData.get("nickname");
  const account = formData.get("account");
  const password = formData.get("password");
  // Simple validation
  const res = { fail: true };
  res.err = await registerUser({ nickname, account, password });
  if (res.err === "") {
    return res;
  } else {
    return res;
  }
}

// 定义一个默认的主题对象
const defaultTheme = createTheme();
/**
 * 这是注册的组件
 * @param {*} param0
 * @returns
 */
export default function Register() {
  // 状态和事件处理函数
  // 使用useAuth钩子来处理注册逻辑
  const [nickname, setNickname] = useState("");
  const [account, setAccount] = useState("");
  const [password, setPassword] = useState("");
  // 密码状态
  const [showPassword, setShowPassword] = useState(false);
  const passwordType = showPassword ? "password" : "text";

  // 密码明文状态转换
  const toChangePasswordState = () => {
    setShowPassword((prevState) => !prevState);
  };
  // Snackbar
  const [snackbarMes, setSnackbarMes] = useState({
    text: undefined,
    open: false,
    severity: "warning",
  });
  // Submit and action outcome
  const submit = useSubmit();
  const res = useActionData();
  const navigate = useNavigate();
  useEffect(() => {
    if (res?.fail && res.err !== "") {
      setSnackbarMes({ text: res.err, open: true, severity: "error" });
    } else if (res?.err === "") {
      setSnackbarMes({
        text: "注册成功，马上返回登录页面",
        open: true,
        severity: "success",
      });
      //三秒后返回主页面
      setTimeout(() => {
        navigate("/login");
      }, 3000);
    }
  }, [res]);

  //注册
  const handleRegister = async (e) => {
    e.preventDefault();
    const err = validateRegisterData(nickname, account, password);
    if (err.length === 0) {
      submit(
        { nickname, account, password },
        {
          method: "post",
          encType: "application/x-www-form-urlencoded",
        }
      );
    } else {
      setSnackbarMes({ text: err, open: true, severity: "error" });
    }
  };

  return (
    // Register组件的JSX结构
    <ThemeProvider theme={defaultTheme}>
      <LoginRegisterContainer>
        <Avatar sx={{ m: 1, bgcolor: "grey.150" }}>
          <LockOutlinedIcon />
        </Avatar>
        <Typography component="h1" variant="h5">
          注册
        </Typography>

        <Box
          component="form"
          noValidate
          onSubmit={handleRegister}
          sx={{ mt: 3 }}>
          <Grid container spacing={2}>
            {/* 昵称 */}
            <Grid item xs={12}>
              <TextField
                required
                fullWidth
                id="nickname"
                label="昵称"
                name="nickname"
                value={nickname}
                onChange={(e) => setNickname(e.target.value)}
              />
            </Grid>
            {/* 用户名 */}
            <Grid item xs={12}>
              <TextField
                required
                fullWidth
                id="accountRegister"
                label="账号"
                name="accountRegister"
                value={account}
                onChange={(e) => setAccount(e.target.value)}
              />
            </Grid>

            {/* 密码 */}
            <Grid item xs={12}>
              <TextField
                required
                fullWidth
                name="passwordRegister"
                label="密码"
                type={passwordType}
                id="passwordRegister"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                InputProps={{
                  endAdornment: (
                    <InputAdornment position="end">
                      <IconButton onClick={toChangePasswordState} edge="end">
                        {showPassword ? <VisibilityOff /> : <Visibility />}
                      </IconButton>
                    </InputAdornment>
                  ),
                }}
              />
            </Grid>
          </Grid>

          {/* 注册键 */}
          <Button
            type="submit"
            fullWidth
            variant="contained"
            sx={{ mt: 3, mb: 2 }}>
            注册
          </Button>

          {/* 跳转登录界面 */}
          <Grid container justifyContent="flex-end">
            <Grid item>
              <Button variant="body2" component={Link} to={"/login"}>
                已拥有用户名? 登录
              </Button>
            </Grid>
          </Grid>
        </Box>
        {/* 版权信息 */}
        <Copyright sx={{ mt: 8, mb: 2 }} />
      </LoginRegisterContainer>
      <LilySnack
        duration={snackbarMes.duration}
        open={snackbarMes.open}
        onClose={(event, reason) => {
          if (reason === "clickaway") {
            return;
          }
          setSnackbarMes({ ...snackbarMes, open: false });
        }}
        severity={snackbarMes.severity}
        text={snackbarMes.text}
      />
    </ThemeProvider>
  );
}
